const fp = require('fastify-plugin')
const { WXMINIUser } = require('wx-js-utils')
const axios = require('axios')

module.exports = fp(async (fastify, opts) => {
  const appConfig = {
    appId: 'wx08a681f9398ba8cc',
    secret: '93cede9e1ca6e0d44f4ee5d67aff711a',
  }
  const wXMINIUser = new WXMINIUser(appConfig)

  fastify.decorate('invokeCloudFunction', async (functionName, params) => {
    const env =
      process.env.ENV === 'prod'
        ? 'cloud1-6gz5djk7129fed5a'
        : 'wbg-business-dev-av7lc'
    const token = await wXMINIUser.getAccessToken()

    let {
      data: { errcode, errmsg, resp_data: data },
    } = await axios.post(
      'https://api.weixin.qq.com/tcb/invokecloudfunction',
      params,
      { params: { access_token: token, env, name: functionName } }
    )
    if (errcode) {
      throw new Error(errmsg)
    }
    data = JSON.parse(data)

    return data
  })
})
